package post

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/logic/util"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetForumPostListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetForumPostListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetForumPostListLogic {
	return &GetForumPostListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 香评列表 ##25.03.22## 历史遗留文件，暂不处理
func (l *GetForumPostListLogic) GetForumPostList(req *types.PostListReq) (*types.PostListInfo, error) {
	//开局定义限制条件:1.用户id校验 2.解析page,pagesize 3.定义逻辑常量
	userId := jwt.GetUserId(l.ctx) //做过userid校验了

	//解析page,pagesize
	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	//根据常量可以知道后面要做哪些校验
	var (
		filters []string //条件过滤
		// skipParent      bool                                                        //跳过父类香水
		// skipLevel       bool                                                        //跳过用户等级
		sorter          *string                                                     //排序
		platformId      uint32             = globalkey.ThirdPartyPlatformWechatMini //针对微信小程序平台
		hasNextPage     bool                                                        //下一页（末页判定)
		hasPreviousPage bool                                                        //上一页(首页判定)
		photos          []*types.MediaInfo                                          //图片信息获取
		author          *types.AuthorInfo                                           //作者信息
		// anonymous       *bool                                                       //针对作者是否匿名选项
		// // perfumeMap      map[uint64]*types.KbEntryInfo     //主要用于获取标题，其他字段想用哪些都可以拿
		// // perfumeIds []uint64
		// perfumeIds []uint64 //自己写了个获取title的函数
		url string //图片url
		//title *string //香评title
	)

	//校验从上下文获取的uid是否和用户id匹配，如果匹配，就给private的标签
	var uid uint64
	if req.UserId != nil && *req.UserId > 0 {
		uid = *req.UserId
	} else {
		uid = userId
	}

	//当uid == userId private为true，不等为false
	private := uid == userId

	//过滤获取指定香评id
	filters = append(filters, "ForumId,equalTo:"+strconv.FormatInt(l.svcCtx.Config.Query.PostForumId, 10))
	//如果用户设置了个人过滤，解析过滤并且添加到过滤列表
	if req.Filter != nil && len(strings.TrimSpace(*req.Filter)) > 0 {
		filterMap := util.GetFilterMap(strings.TrimSpace(*req.Filter))
		for key, val := range filterMap {
			switch key {
			case "sticky": // todo: 使用场景未知
				filters = append(filters, "Sticky,equalTo:"+val)
			}
		}
	}

	if req.ParentId != nil && *req.ParentId > 0 { // 指定香水
		private = false // 大家的香评
		// skipParent = true
		// preload += ",AuthorName,AuthorAvatar,AuthorIp,AuthorLevel"
		// eagerLoad += ",total"
		filters = append(filters, "ParentId,equalTo:"+strconv.FormatUint(*req.ParentId, 10))
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	} else if private { // 我的香评
		// skipLevel = true
		filters = append(filters, "AuthorId,equalTo:"+strconv.FormatUint(uid, 10))
		filters = append(filters, "Status,notEqualTo:"+strconv.FormatInt(int64(globalkey.StatusDeleted), 10))
	} else { // 别人的香评
		// skipLevel = true
		filters = append(filters, "AuthorId,equalTo:"+strconv.FormatUint(uid, 10))
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	}

	if req.Sorter != nil {
		sorter = pointy.GetPointer(strings.TrimSpace(*req.Sorter))
	}

	//获取香评列表
	res, err := l.svcCtx.ForumRpc.GetPostList(l.ctx, &forumclient.BaseListReq{
		Offset: uint32((page - 1) * pageSize),
		Limit:  uint32(pageSize),
		// Preload:    pointy.GetPointer(preload),
		// EagerLoad:  pointy.GetPointer(eagerLoad),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		Sorter:     sorter,
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(platformId),
	})
	if err != nil {
		logx.Errorw("获取香评列表失败")
		return nil, err
	}

	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	resp := &types.PostListInfo{
		BaseListInfo: types.BaseListInfo{
			Total:           res.Total,
			Current:         page,
			PageSize:        pageSize,
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	if len(res.List) > 0 {
		//获取图片信息
		for _, v := range res.List {
			for _, m := range v.Media {
				if len(v.Media) > 0 {
					if m.Url != nil && len(*m.Url) > 0 {
						url = *m.Url
					}
					if len(url) == 0 && m.Uri != nil && len(*m.Uri) > 0 {
						url = *m.Uri
					}
					photos = append(photos, &types.MediaInfo{
						Uid:     m.Uid,
						Id:      m.Id,
						Url:     pointy.GetPointer(url),
						AltText: m.AltText,
						Details: m.MetaData,
					})
				}
			}

			//if v.Title != nil {
			//	title = v.Title
			//} else {
			//	title = pointy.GetPointer("Untitled")
			//}

			//获取Postinfo，包括作者以及作品title
			resp.List = append(resp.List, &types.PostInfo{
				Id: v.Id,
				// ContentHtml:  v.ContentHtml,
				Author:   author,
				AuthorId: v.AuthorId,
				// ParentId:     v.ParentId,
				Photos: photos,
				//Title:  title,
				// Grade:        v.AverageRating,
				// Status:       v.Status,
				// CommentCount: v.CommentCount,
				UpdatedAt: v.CreatedAt,
			})
		}
	}

	return resp, nil
}
